package com.tticar.invmanager.service.impl;

import com.baomidou.mybatisplus.entity.Columns;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tticar.invmanager.common.Enum.CodeType;
import com.tticar.invmanager.common.Enum.Status;
import com.tticar.invmanager.common.utils.ServiceUtil;
import com.tticar.invmanager.entity.*;
import com.tticar.invmanager.entity.vo.MyPage;
import com.tticar.invmanager.mapper.PPurchaseDetailMapper;
import com.tticar.invmanager.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 采购单详情 服务实现类
 * </p>
 *
 * @author joeyYan
 * @since 2018-08-03
 */
@Service
public class PPurchaseDetailServiceImpl extends ServiceImpl<PPurchaseDetailMapper, PPurchaseDetail> implements IPPurchaseDetailService {

    @Autowired
    IWWearhouseService wearhouseService;
    @Autowired
    IWPositionService positionService;
    @Autowired
    IPPurchaseService purchaseService;
    @Autowired
    ICodeCounterService codeCounterService;
    @Autowired
    IInRepositoryDetailService inRepositoryDetailService;
    @Autowired
    IRepositoryCountService repositoryCountService;

    @Override
    public List selectMapList(Long purchaseId) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.ne(Status.STATUS.getDesc(), Status.DELETE.getCode());
        Columns column = Columns.create().column("*");
        column.column("(select name from m_materiel where id =(select mid from m_materiel_sku where id=sku_id))", "materielName");
        column.column("(select default_whouse_id from m_materiel where id =(select mid from m_materiel_sku where id=p_purchase_detail.sku_id))", "whouseId");
        column.column("(select default_position_id from m_materiel where id =(select mid from m_materiel_sku where id=p_purchase_detail.sku_id))", "positionId");
        wrapper.setSqlSelect(column);
        wrapper.eq("purchase_id", purchaseId);
        List<Map<String, Object>> list = this.selectMaps(wrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            for (Map<String, Object> map : list) {
                // 未入库的给出默认的库位
                if ((int)map.get("status") == 0) {
                    WWearhouse wearhouse = wearhouseService.selectById((Long)map.get("whouseId"));
                    WPosition position = positionService.selectById((Long)map.get("positionId"));
                    String houseName = wearhouse == null ? "" : wearhouse.getName();
                    String positionName = position == null ? "" : position.getName();
                    map.put("house", houseName + ":" + positionName);
                }

            }
        }
        return list;
    }

    @Override
    public Page selectPage(PPurchaseDetail pPurchaseDetail, MyPage<PPurchaseDetail> page) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.ne(Status.STATUS.getDesc(), Status.DELETE.getCode());
        Columns column = Columns.create().column("*");
        column.column("(select name from m_materiel where id =(select mid from m_materiel_sku where id=sku_id))", "materiel_name");
        wrapper.setSqlSelect(column);
        //wrapper.like(Strings.isNotEmpty(pPurchaseDetail.getName()), PPurchaseDetail.NAME, pPurchaseDetail.getName());
        return this.selectMapsPage(page, wrapper);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> ids) {
        List list = new ArrayList();
        for (Long id : ids) {
            PPurchaseDetail pPurchaseDetail = new PPurchaseDetail();
            pPurchaseDetail.setId(id);
            list.add(pPurchaseDetail);
        }
        this.updateBatchById(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void detailInRepository(List<PPurchaseDetail> details, Long purchaseId) {
        if (CollectionUtils.isEmpty(details)) {
            return;
        }
        PPurchase pPurchase = purchaseService.selectById(purchaseId);
        Date orderTime = new Date();
        String code = codeCounterService.getOrderCode(CodeType.RK);
        String username = ServiceUtil.getLoginUserName();
        for (PPurchaseDetail param : details) {
            PPurchaseDetail detail = this.selectById(param.getId());
            if (detail.getStatus() == 1) {
                continue; // 已经入库的忽略
            }
            InRepositoryDetail inRepositoryDetail = new InRepositoryDetail();
            inRepositoryDetail.setProviderId(pPurchase.getRelativeId());
            inRepositoryDetail.setOrderTime(orderTime);
            inRepositoryDetail.setCode(code);
            inRepositoryDetail.setUsername(username);

            inRepositoryDetail.setBuszId(detail.getId());
            inRepositoryDetail.setBatchNumber(detail.getBatchCode());
            inRepositoryDetail.setSkuId(detail.getSkuId());
            inRepositoryDetail.setCount(detail.getCountActual());

            inRepositoryDetail.setRemark(param.getRemark());
            inRepositoryDetail.setPositionId(param.getPositionId());
            inRepositoryDetail.setWearhouseId(param.getWearhouseId());
            // 入库
            inRepositoryDetailService.insert(inRepositoryDetail);

            // 更新库存数量
            repositoryCountService.updateRepositoryCount(
                    inRepositoryDetail.getSkuId(), inRepositoryDetail.getWearhouseId(),  inRepositoryDetail.getCount());

            // 采购单更新为已入库
            PPurchaseDetail detailUpdate = new PPurchaseDetail();
            detailUpdate.setId(detail.getId());
            detailUpdate.setRemark(param.getRemark());
            detailUpdate.setStatus(1);
            this.updateById(detailUpdate);
        }
    }

}
